package com.wufeng.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wufeng.dto.R;
import com.wufeng.entity.ChatRecord;
import com.wufeng.entity.EvaluateQuestion;
import com.wufeng.entity.QuestionOption;
import com.wufeng.service.ChatRecordService;
import com.wufeng.service.EvaluateQuestionService;
import com.wufeng.service.QuestionOptionService;
import com.wufeng.service.cache.CacheService;
import com.wufeng.utils.SmsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 测试
 */
@RestController
@RequestMapping("/test")
public class TestController {


    @Autowired
    private SmsUtil smsUtil;

    @Autowired
    private CacheService cacheService;

    @Autowired
    private EvaluateQuestionService evaluateQuestionService;

    @Autowired
    private QuestionOptionService questionOptionService;

    @Autowired
    private ChatRecordService chatRecordService;


    @GetMapping("/getChatRecords")
    public R getChatRecords(){
        List<ChatRecord> list = chatRecordService.list();
        HashMap<String, Object> map = new HashMap<>();
        map.put("list",list);
        return R.ok(map);
    }

    /**
     * 测试发送验证码
     *
     * @param number
     * @return
     */
    @GetMapping("/sms")
    public R sendSms(@RequestParam String number) {
        smsUtil.sendSMS(number, "202418",null);

        return R.ok();
    }


    @GetMapping("/redis")
    public void testRedis() {
        //測試redis
        System.out.println("测试redis");
        cacheService.add("test", "5647");

        String test = cacheService.get("test");
        System.out.println(test);


    }

    /**
     * 插入测试数据
     *
     * @param map
     */
    @PostMapping("/insertData")
    @Transactional
    public void insertData(@RequestBody HashMap<String, Object> map) {

        //需要将拿到的json数据先改一下code，改成evaluateId
        Integer code = (Integer) map.get("code");

        //外键：测试id
        Integer evaluateId = code;

        HashMap data = (HashMap) map.get("data");
        List questions = (List) data.get("questions");
        int questionSort = 1;
        for (Object question : questions) {
//            System.out.println(question);
            HashMap questionMap = (HashMap) question;
//            System.out.println(questionMap);
            String title = (String) questionMap.get("title");
            String picture = (String) questionMap.get("picture");

            EvaluateQuestion evaluateQuestion = new EvaluateQuestion();
            evaluateQuestion.setEvaluateid(evaluateId);
            evaluateQuestion.setSort(questionSort);
            evaluateQuestion.setTitle(title);
            evaluateQuestion.setImage(picture);
            //将evaluateQuestion插入表中
            evaluateQuestionService.save(evaluateQuestion);
            questionSort++;

            //获取表中最后一条数据，即刚插入的数据
//            EvaluateQuestion last = evaluateQuestionService.getOne(new QueryWrapper<EvaluateQuestion>().last("LIMIT 1"));
            Integer questionId = evaluateQuestion.getQuestionid();

            List options = (List) questionMap.get("options");
            List<QuestionOption> list = new ArrayList<>();
            int option_sort = 1;
            for (Object option : options) {
                HashMap optionMap = (HashMap) option;
                String optionTitle = (String) optionMap.get("title");
                String value = (String) optionMap.get("value");
                QuestionOption questionOption = new QuestionOption();
                questionOption.setQuestionid(questionId);
                questionOption.setTitle(optionTitle);
                questionOption.setValue(value);
                questionOption.setSort(option_sort++);
                list.add(questionOption);

            }
            System.out.println(list);
            //批量保存
            questionOptionService.saveBatch(list);

        }
    }


    @GetMapping("/insertResult")
    @Transactional
    public R insertResult(@RequestParam("evaluateId") Integer evaluateId) {

        List<EvaluateQuestion> questions = evaluateQuestionService.list(new QueryWrapper<EvaluateQuestion>().eq("evaluateId", evaluateId));

        List<Integer> questionIds = questions.stream().map(question -> question.getQuestionid()).collect(Collectors.toList());


        List<QuestionOption> list = questionOptionService.list(new QueryWrapper<QuestionOption>().in("questionId", questionIds));


        Map<Integer, List<QuestionOption>> collect =
                list.stream().collect(Collectors.groupingBy(QuestionOption::getQuestionid));


        System.out.println("size:" + questions.size());

        //计算每个题多少分，保留三位小数
        Double perScore = 100.0 / questions.size();
        String formattedPerScore = String.format("%.3f", perScore);
        perScore = Double.parseDouble(formattedPerScore);

        Collection<List<QuestionOption>> values = collect.values();
        for (List<QuestionOption> value : values) {
            //每个value都是一组选项

            // 打乱列表顺序
            Collections.shuffle(value);
            //随机将其中一个QuestionOption的分数置为perScore,剩下的置为0

            // 随机将其中一个QuestionOption的分数置为perScore，剩下的置为0
            if (!value.isEmpty()) {
                // 设置一个随机索引，将该索引的元素的分数设为perScore，其他的设为0
                int randomIndex = new Random().nextInt(value.size());
                for (int i = 0; i < value.size(); i++) {
                    double score = (i == randomIndex) ? perScore : 0.0;
                    value.get(i).setScore(score);
                }
            }

            //将value写到数据库，update
            questionOptionService.saveOrUpdateBatch(value);
        }

        HashMap<String, Object> map = new HashMap<>();
//        map.put("list",list);
        map.put("collect", collect);
        return R.ok(map);
    }

}
